import { playerSignupTypeEnum } from 'src/common/constant/enums';
import { Event } from 'src/modules/event/entities/event.entity';
import { StageEvent } from 'src/modules/stage-event/entities/stage-event.entity';
import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  ManyToOne,
  JoinColumn,
  BeforeInsert,
  BeforeUpdate,
  OneToMany,
} from 'typeorm';

/**
 * 用于保存比赛的报名信息
 */
@Entity('player_signup')
export class PlayerSignup {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;

  @Column()
  phone: string;

  @Column()
  email: string;

  @Column()
  idCard: string;

  @Column()
  age: number;

  @Column()
  gender: 'male' | 'female';

  @Column()
  address: string;

  @Column()
  organization: string;

  @ManyToOne(() => Event)
  @JoinColumn({ name: 'fk_eventId' })
  event: Event;

  @ManyToOne(() => StageEvent)
  @JoinColumn({ name: 'fk_stage_eventId' })
  stageEvent: StageEvent;

  @Column({ name: 'fk_eventId' })
  eventId: number;

  @Column({ name: 'fk_stage_eventId' })
  stageEventId: number;

  @Column()
  createBy: number;

  @Column()
  createTime: Date;

  @Column()
  updateBy: number;

  @Column()
  updateTime: Date;

  @BeforeInsert()
  BeforeInsert?() {
    this.createTime = new Date();
    this.updateTime = this.createTime;
    if (this._order === null) {
      this._order = -1;
    }
  }

  @BeforeUpdate()
  BeforeUpdate?() {
    this.updateTime = new Date();
    if (this._order === null) {
      this._order = -1;
    }
  }

  @Column()
  pairName: string;

  @Column()
  isMainPlayer: boolean;

  @Column({ name: 'fk_parentPlayerId' })
  parentPlayerId: number;

  @JoinColumn({ name: 'fk_parentPlayerId' })
  @ManyToOne(
    () => PlayerSignup,
    (playerSignup) => playerSignup.subPlayerSignups,
  )
  parentPlayerSignup: PlayerSignup;

  // @JoinColumn({ name: 'id' })
  @OneToMany(
    () => PlayerSignup,
    (playerSignup) => playerSignup.parentPlayerSignup,
    {
      cascade: true,
    },
  )
  subPlayerSignups: PlayerSignup[];

  // 这个在confirmE2P的时候会用到
  @Column({ name: 'order' })
  _order: number | null;

  @Column()
  key: string;

  @Column()
  type: playerSignupTypeEnum;

  @Column({ name: 'copyFromId' })
  copyFromId: number;
}
